package com.dmz.wxcp.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmz.wxcp.constants.Constant;
import com.dmz.wxcp.redis.RedisUtils;
import com.dmz.wxcp.wecom.common.service.RedisService;
import com.dmz.wxcp.wecom.contact.entity.Contact;
import com.dmz.wxcp.wecom.contact.service.ContactService;
import com.dmz.wxcp.wecom.signature.service.MP_OAuth2Service;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

public class SignatureInterceptor implements HandlerInterceptor {

    private String appid="wx67c889e976f55f93";

    private RedisService redisService;

    private WxMpService wxMpService;

    private MP_OAuth2Service cpOAuth2Service;


    private ContactService contactService;

    public SignatureInterceptor(RedisService redisService,ContactService contactService,
                                WxMpService wxMpService,MP_OAuth2Service cpOAuth2Service){
        this.redisService=redisService;
        this.wxMpService=wxMpService;
        this.cpOAuth2Service=cpOAuth2Service;
        this.contactService=contactService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String backURL = request.getRequestURL().toString();
        String code = request.getParameter("code");
        if (request.getQueryString() != null) {
            backURL += "?" + request.getQueryString();

        }



        HttpSession session = request.getSession();

        String userAgent = request.getHeader("User-Agent");

//判断是否是微信浏览器

        if (userAgent == null || !userAgent.toLowerCase().contains("micromessenger")) {
            return true;
         }

        String accesstokenkey= Constant.USERINFO_ACCESSTOKEN;

        if (!wxMpService.switchover(appid) ){
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        if(session.getAttribute("contact")!=null){
            System.out.println("----------------"+request.getSession().getAttribute("contact"));
            return true;
        }else{
            // 第一次访问
            if (StringUtils.isBlank(code)) {
                String url=cpOAuth2Service.Oauth(backURL);
                response.sendRedirect(url);
                return false;
            }
        }
        try {
//            首先在Redis中查找是否有token
            WxOAuth2AccessToken accessToken=new WxOAuth2AccessToken();
            if (redisService.hasKey(accesstokenkey)) {
                accessToken= RedisUtils.RedisToObject((String)redisService.get(accesstokenkey),WxOAuth2AccessToken.class);
                if (!wxMpService.getOAuth2Service().validateAccessToken(accessToken)) {
                    accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
                    redisService.set(accesstokenkey,accessToken,3600, TimeUnit.SECONDS);
                }
            }else{
                accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
                redisService.set(accesstokenkey,accessToken,3600, TimeUnit.SECONDS);
            }
//            获取微信用户信息
            WxOAuth2UserInfo user = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            Contact contact=new Contact();
//            现在contact表中查找是否有当前微信用户记录
            if(contactService.selectCountByOpenId(user.getOpenid())==0){
//                如果没有就新增
                contact.setOpenid(user.getOpenid());
                contact.setNickname(user.getNickname());
                contact.setCity(user.getCity());
                contact.setCountry(user.getCountry());
                contact.setHeadimgurl(user.getHeadImgUrl());
                contact.setProvince(user.getProvince());
                contact.setSex(user.getSex()==1);
                contactService.save(contact);
            }else {
//                如果有就查询出来放入session
                QueryWrapper<Contact> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("openid",user.getOpenid());
                contact=contactService.getOne(queryWrapper);
            }
            session.setAttribute("contact",contact);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }


        return true;

    }
}
